package com.gitee.fastmybatis.spring.boot.autoconfigure.util;

import com.gitee.fastmybatis.core.handler.BaseFill;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class FillUtil {


    public static List<BaseFill<?>> buildFills(Map<String, String> fillMap) {
        Set<Map.Entry<String, String>> entrySet = fillMap.entrySet();
        List<BaseFill<?>> fillList = new ArrayList<>(entrySet.size());
        String className = "", parameter = "";
        try {
            for (Map.Entry<String, String> entry : entrySet) {
                className = entry.getKey();
                parameter = entry.getValue();
                BaseFill<?> handler = (BaseFill<?>) buildInstance(className, parameter);
                fillList.add(handler);
            }
            return fillList;
        } catch (ClassNotFoundException e) {
            throw new RuntimeException("属性[mybatis.fill." + className + "=" + parameter + "]设置错误.类" + className + "不存在", e);
        } catch (Exception e) {
            String errorMsg = "属性[mybatis.fill." + className + "=" + parameter + "]设置错误,检查类是否存在并继承com.gitee.fastmybatis.core.handler.FillHandler";
            throw new RuntimeException(errorMsg, e);
        }
    }

    private static Object buildInstance(String className, String parameter) throws ClassNotFoundException, Exception {
        // 根据类名获取Class对象
        Class<?> clazz = Class.forName(className);

        if (StringUtils.hasLength(parameter)) {
            // 参数类型数组
            Class<?>[] parameterTypes = {String.class};
            // 根据参数类型获取相应的构造函数
            java.lang.reflect.Constructor<?> constructor = clazz.getConstructor(parameterTypes);
            // 根据获取的构造函数和参数，创建实例
            return constructor.newInstance(parameter);
        } else {
            return clazz.newInstance();
        }
    }

}
